<template>
    <div class="add_box">
        <el-alert title="添加商品信息" type="info" center :closable="false" show-icon> </el-alert>
        <el-steps align-center :active="activeIndex*1" finish-status="success">
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>

        <el-form :model="addForm" :rules="rules" ref="addFormRef" label-position="top" label-width="100px">
            <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeTabLeave">
                <el-tab-pane label="基本信息" name="0">
                    <el-form-item label="商品名称" prop="goods_name">
                        <el-input v-model="addForm.goods_name"></el-input>
                    </el-form-item>

                    <el-form-item label="商品价格" prop="goods_price">
                        <el-input v-model="addForm.goods_price"></el-input>
                    </el-form-item>

                    <el-form-item label="商品重量" prop="goods_weight">
                        <el-input v-model="addForm.goods_weight" type="number"></el-input>
                    </el-form-item>

                    <el-form-item label="商品数量" prop="goods_number">
                        <el-input v-model="addForm.goods_number" type="number"></el-input>
                    </el-form-item>

                    <el-form-item label="商品分类" prop="goods_cat">
                        <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="cateProps"
                            @change="handleChange"></el-cascader>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品参数" name="1">
                    <el-form-item v-if="mm.length" v-for="item in mm" :label="item.attr_name"
                        :key="item.attr_id">
                        <el-checkbox-group v-model="item.attr_vals">
                            <el-checkbox border :label="item" v-for="(item, i) in item.attr_vals" :key="i">{{ item }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-alert v-else title="无可用参数" type="success" center :closable="false"> </el-alert>
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="2">
                    <el-form-item v-if="m1.length" v-for="item in m1" :label="item.attr_name"
                        :key="item.attr_id">
                        <el-input v-model="item.attr_vals"></el-input>
                    </el-form-item>
                    <el-alert v-else title="无可用属性" type="success" center :closable="false"> </el-alert>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="3">
                    <el-upload class="upload-img" :action="uploadUrl" :on-preview="handlePreview"
                        :on-remove="handleRemove" list-type="picture" :headers="headersObj" :on-success="handleSuccess">
                        <el-button type="primary" class="uploadBtn">点击上传</el-button>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name="4">
                    <QuillEditor theme="snow" class="richText" v-model:content="addForm.introduce" />
                    <el-button type="primary" class="AddBtn" @click="addShop(addFormRef)">添加商品</el-button>
                </el-tab-pane>
            </el-tabs>
        </el-form>
        <el-dialog title="图片预览" v-model="previewDialogVisible" width="50%">
            <img :src="previewPath" alt="" class="perviewImg" />
        </el-dialog>
    </div>
</template>
<script setup>
    import {
        ElMessage, ElAlert, ElDialog,
        ElSteps, ElStep,
        ElTabs, ElTabPane,
        ElForm, ElFormItem, ElCascader,
        ElInput, ElButton, ElUpload,
        ElCheckbox, ElCheckboxGroup
    } from "element-plus"
    import { QuillEditor } from '@vueup/vue-quill'
    import '@vueup/vue-quill/dist/vue-quill.snow.css';
    import {
        getCategories,
        getCateAttrs,
        uploadUrl,
        postAddGoods
    } from "@/tools/ajax"
    import { ref, reactive } from "vue"
    import { useRouter } from "vue-router"
    import { useRules } from "@/tools/utils"
    const activeIndex = ref('0') 
    const addForm = reactive({
        goods_cat: [],
        pics: [],
        attrs: [],
        introduce: ""
    })
    const addFormRef = reactive({}) 
    const {
        goodsNameRule,
        goodsPriceRule,
        goodsNumberRule,
        goodsWeightRule,
        goodsCateRule
    } = useRules() 
    const rules = {  
        goods_name: goodsNameRule,
        goods_price: goodsPriceRule,
        goods_number: goodsNumberRule,
        goods_weight: goodsWeightRule,
        goods_cat: goodsCateRule
    }
    const cateList = reactive([])
    const cateProps = {   
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
    }
    getCategories().then(res => {
        if (res.meta.status != 200) return ElMessage.error(res.meta.msg)
        cateList.push(...res.data)
    })
    const mm = reactive([])
    const m1 = reactive([])
    async function handleChange() {
        const res = await getCateAttrs({
            id: addForm.goods_cat[addForm.goods_cat.length - 1],
            sel: "many",
        })
        if (res.meta.status !== 200) return ElMessage.error('获取此分类动态参数失败!')
        res.data.forEach(item => {
            if (item.attr_vals.length === 0) {
                item.attr_vals = []
            } else {
                item.attr_vals = item.attr_vals.split(' ')
            }
        })
        console.log(res.data)
        mm.push(...res.data)
        const res2 = await getCateAttrs({
            id: addForm.goods_cat[addForm.goods_cat.length - 1],  
            sel: "only",
        })
        if (res2.meta.status !== 200) return ElMessage.error('获取此分类静态属性失败!')
        res2.data.forEach(item => {
            if (item.attr_vals.length === 0) {
                item.attr_vals = []
            } else {
                item.attr_vals = item.attr_vals.split(' ')
            }
        })
        console.log(res2.data)
        m1.push(...res2.data)
    }
    function beforeTabLeave(newName, oldName) { 
        if ((newName == "1" || newName == "2") && addForm.goods_cat.length == 0) {
            ElMessage.error('请先选择商品分类!')
            return false 
        }
    }
    const headersObj = {
        Authorization: window.sessionStorage.getItem('token')
    }
    const previewPath = ref("") 
    const previewDialogVisible = ref(false) 
    function handlePreview(file) { 
        console.log(file.response.data.url);
        previewPath.value = file.response.data.url
        previewDialogVisible.value = true
    }
    function handleSuccess(resposne) { 
        const picInfo = { pic: resposne.data.tmp_path }
        addForm.pics.push(picInfo)
    }
    function handleRemove(file) { 
        console.log('移除图片1', file, addForm.pics)
        const filePath = file.response.data.tmp_path
        const index = addForm.pics.findIndex(x => x.pic === filePath)
        addForm.pics.splice(index, 1)
        console.log('移除图片2', addForm.pics)
    }
    const router = useRouter()
    function addShop(form) { 
        console.log(addForm);
        form.validate(async bool => {
            if (!bool) return ElMessage.error("请正确填写商品信息!");
            addForm.goods_cat = addForm.goods_cat.join(",")
            addForm.introduce = addForm.introduce.ops && addForm.introduce.ops[0].insert
            mm.forEach(item => {
                const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
                addForm.attrs.push(newInfo)
            })
            m1.forEach(item => {
                const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
                addForm.attrs.push(newInfo)
            })
            console.log(addForm);
            const { meta: res } = await postAddGoods(addForm)
            console.log(res);
            if (res.status != 201) return ElMessage.error(res.msg)
            ElMessage.success(res.msg)
            router.push("/goods")
        })
    }
    // #endregion
</script>

<style lang="scss" scoped>
    .el-steps {
        margin-top: 15px;
    }

    :deep(.el-tabs__nav) {
        height: calc(100vh - 290px);
        display: flex;
        flex-direction: column;
        justify-content: space-evenly;
    }

    :deep(.el-tabs__content) {
        height: calc(100vh - 290px);
        overflow: auto;
    }

    :deep(.el-cascader) {
        width: 240px;
    }

    :deep(.el-form-item__label) {
        margin-top: 15px;
    }

    :deep(.richText) {
        height: calc(100vh - 380px);
    }

    .el-step__title {
        font-size: 13px;
    }

    .el-input {
        width: 95%;
    }

    .uploadBtn {
        margin: 15px;
    }

    .AddBtn {
        margin-top: 15px;
    }

    .perviewImg {
        width: 100%;
    }
</style>